package handler.impl;/*
* @auther 顶风少年 
* @mail dfsn19970313@foxmail.com
* @date 2020-01-10 15:53
* @notify 
* @version 1.0
*/

import handler.ResultSetHandler;
import mapping.MappedStatement;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class DefaultResultSetHandler<E> implements ResultSetHandler {
    @Override
    public List<E> handleResultSet(MappedStatement mappedStatement,ResultSet resultSet)throws Exception{
        //查询返回值类型
        Class<?> resultTypeClass = mappedStatement.getResultTypeClass();
        //创建返回值集合
        List<Object> results = new ArrayList<>();
        //获取一行数据
        while (resultSet.next()) {
            //创建返回值对象
            Object clo = resultTypeClass.newInstance();
            //获取行属性
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取列字段个数
            int columnCount = metaData.getColumnCount();
            //遍历字段
            for (int i = 0; i < columnCount; i++) {
                //获取列名
                String columnClassName = metaData.getColumnName(i + 1);
                //获取列值
                Object object = resultSet.getObject(columnClassName);
                //通过反射拿到列，此处必须保证类名有对应的属性名
                Field declaredField = resultTypeClass.getDeclaredField(columnClassName);
                declaredField.setAccessible(true);
                //设置属性值
                declaredField.set(clo, object);
            }
            //将每一行添加到集合
            results.add(clo);
        }
        return (List<E>)results;
    }
}
